﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.DBContext;
using Guoc.BigMall.Application.DTO;
using Guoc.BigMall.Application.Search;
using Guoc.BigMall.Application.ViewObject;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Extension;
using AutoMapper;
namespace Guoc.BigMall.Application.Facade
{
    public class DistributeFacade : IDistributeFacade
    {
        IDBContext _db;
        readonly int _DistributeLevel = 7;
        public DistributeFacade(IDBContext dbContext)
        {
            this._db = dbContext;

        }
        public void Save(DistributeModel model)
        {
            model.CheckLevelRebate();
            var entity = _db.Table<Distribute>().FirstOrDefault(n => n.ProductId == model.ProductId);
            // 商品分润金额
            if (entity == null)
            {
                entity = model.MapTo<Distribute>();
                _db.Insert(entity);
            }
            else
            {
                entity.Rebate = model.Rebate;
                _db.Update(entity);
            }
            // 多级分销金额
            var items = _db.Table<DistributeRebate>().Where(n => n.ProductId == model.ProductId).ToList();
            if (items.Count == 0)
            {
                items = Mapper.Map<List<DistributeRebateModel>, List<DistributeRebate>>(model.Items);
                _db.Insert(items.ToArray());
            }
            else
            {
                items = Mapper.Map<List<DistributeRebateModel>, List<DistributeRebate>>(model.Items);
                _db.Update(items.ToArray());
            }

            _db.SaveChange();
        }

        public void Edit(DistributeModel model)
        {
            throw new NotImplementedException();
        }

        public DistributeModel GetById(int productId)
        {
            var sql = @"select p.Id as ProductId, p.Name as ProductName,p.Code aS ProductCode,P.SalePrice,d.* from Product p left join Distribute d  on d.ProductId =p.Id where p.Id = @ProductId ";

            var entity = _db.DataBase.QuerySingle<DistributeModel>(sql, new { ProductId = productId });

            if (entity == null)
                throw new FriendlyException("商品:{0} 不存在".FormatWith(productId));

            var entityItems = _db.Table<DistributeRebateModel>().Where(n => n.ProductId == productId).ToList();

            entity.Items = entityItems;
            if (entity.Items.Count == 0)
            {
                for (int i = 1; i <= _DistributeLevel; i++)
                {
                    entity.Items.Add(new DistributeRebateModel()
                    {
                        Level = i,
                        ProductId = entity.ProductId
                    });
                }
            }

            return entity;
        }

        public IEnumerable<DistributeDto> GetList(Pager page, SearchDistribute search)
        {
            IEnumerable<DistributeDto> rows;
            dynamic param = new ExpandoObject();
            string where = "";
            if (search.ProductCode.NotNullOrEmpty())
            {
                where += " and  p.Code like @ProductCode";
                param.ProductCode = string.Format("%{0}%", search.ProductCode);
            }

            if (search.ProductName.NotNullOrEmpty())
            {
                where += " and p.Name like @ProductName";
                param.ProductName = string.Format("%{0}%", search.ProductName);
            }
            if (search.Status == 1) // 已配置分润
            {
                where += " and  d.Rebate > 0 ";
            }
            if (search.Status == 2)// 未配置分润
            {
                where += " and  d.Rebate is null ";
            }


            string sql = @"with pr as (
	SELECT r.ProductId,
	max( CASE Level WHEN 1 THEN LevelRebate END ) as LevelRebate1,
	max( CASE Level WHEN 2 THEN LevelRebate END ) as LevelRebate2,
	max( CASE Level WHEN 3 THEN LevelRebate END ) as LevelRebate3,
	max( CASE Level WHEN 4 THEN LevelRebate END ) as LevelRebate4,
	max( CASE Level WHEN 5 THEN LevelRebate END ) as LevelRebate5,
	max( CASE Level WHEN 6 THEN LevelRebate END ) as LevelRebate6,
	max( CASE Level WHEN 7 THEN LevelRebate END ) as LevelRebate7
FROM
	Distribute_rebate r 
GROUP BY
	r.ProductId
)
Select d.Id,d.Rebate,p.Id as ProductId,p.SalePrice as SalePrice,p.`Name` as ProductName,p.Code as ProductCode ,pr.*
from Product p left join Distribute d  on d.ProductId = p.Id
left join pr on pr.ProductId = d.ProductId
where 1=1 {0} Order By  Id desc LIMIT {1},{2}";
            sql = string.Format(sql, where, (page.PageIndex - 1) * page.PageSize, page.PageSize);
            rows = _db.DataBase.Query<DistributeDto>(sql, param);
            var sqlcount = string.Format(" SELECT count(1) from Distribute d left join Product p on d.ProductId = p.Id WHERE 1=1 {0} ", where);
            page.Total = this._db.DataBase.ExecuteScalar<int>(sqlcount, param);

            return rows;
        }
    }
}
